package com.spring.datasource.config;

import com.spring.datasource.multi.MultiDatasource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;

@Configuration
public class MultiDatasourceConfiguration {

    @Autowired
    private MasterDatasourceProperties masterDatasourceProperties;

    @Autowired
    private SlaveDatasourceProperties slaveDatasourceProperties;


    @Bean("master")
    public HikariDataSource masterDatasource(){

        HikariDataSource datasource = new HikariDataSource();

        datasource.setJdbcUrl(masterDatasourceProperties.getUrl());
        datasource.setUsername(masterDatasourceProperties.getUsername());
        datasource.setPassword(masterDatasourceProperties.getPassword());
        datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        return datasource;
    }

    @Bean("slave")
    public HikariDataSource slaveDatasource(){

        HikariDataSource datasource = new HikariDataSource();

        datasource.setJdbcUrl(slaveDatasourceProperties.getUrl());
        datasource.setUsername(slaveDatasourceProperties.getUsername());
        datasource.setPassword(slaveDatasourceProperties.getPassword());
        datasource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        return datasource;
    }

    @Bean
    public MultiDatasource multiDatasource(){
        MultiDatasource multiDatasource = new MultiDatasource();

        HashMap<Object, Object> ds = new HashMap<>();

        ds.put("master", masterDatasource());
        ds.put("slave", slaveDatasource());
        multiDatasource.setTargetDataSources(ds);
        multiDatasource.setDefaultTargetDataSource(masterDatasource());
        return multiDatasource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(multiDatasource());
        return jdbcTemplate;
    }

}
